const { getFile } = require('../models/getfile')

const model = require("../models")
const ChatGroup = model.chat_group.ChatGroup
const ChatList = model.chat_list.ChatList
const User = model.user.User
const ShopUser = model.shopUser.ShopUser

exports.group = async(ctx) => {
  const { id, userType } = ctx.request.query
  if (!id || !userType) {
    ctx.fail('参数错误')
    return
  }
  let query
  switch (userType) {
    case 'user': // 商城用户
      query = {
        where: { userId: id }
      }
      break
    case 'admin': // 卖家用户
      query = {
        where: { adminId: id }
      }
      break
  }

  function queryRecord(groupId) {
    return new Promise(async(resove) => {
      const res = await ChatList.findAll({
        where: { groupId },
        order: [['createTime', 'DESC']]
      })
      console.log(res, '组信息')
      const { user, admin } = await getUserInfo(res[0])
      res[0]['user'] = user
      res[0]['admin'] = admin
      res[0]['read'] = res[0]['read'] ? true : false
      res[0]['createTime'] = Date.parse(res[0]['createTime'])
      res[0]['updateTime'] = Date.parse(res[0]['updateTime'])
      resove({
        latestMessage: res[0], // 最新一条消息
        readCount: res.filter(item => item.userType != userType && !item.read).length || 0 // 未读消息数
      })
    })
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const group_data = await ChatGroup.findAll(query)
      console.log(group_data, query)
      if (group_data && group_data.length > 0) {
        let flag = 0
        for (let i = 0; i < group_data.length; i++) {
          queryRecord(group_data[i].groupId).then(data => {
            flag++
            group_data[i]['latestMessage'] = data.latestMessage // 最新一条消息
            group_data[i]['readCount'] = data.readCount // 未读消息数
            console.log(group_data[i])
            if (flag === group_data.length) {
              resolve(group_data)
            }
          })
        }
      } else {
        resolve(group_data)
      }
    })
  }

  const res = await allFn()
  if (res) {
    ctx.success(res, '查询成功')
  } else {
    ctx.fail()
  }
}

exports.record = async(ctx) => {
  const { groupId, page, size, type } = ctx.request.query
  if (!page || !size || !groupId) {
    ctx.fail('参数错误')
    return
  }
  function allFn() {
    return new Promise(async(resolve) => {
      const res = await ChatList.findAndCountAll({
        where: { groupId },
        offset: (parseInt(page) - 1) * parseInt(size),
        limit: parseInt(size),
        order: [['createTime', 'DESC']]
      })

      const readData = res.rows.filter(item => { // 更新为已读数据
        if (item.userType != type) {
          item.read = 1
          return item
        }
      })
      await ChatList.bulkCreate(readData, { updateOnDuplicate:['read']}) //  updateOnDuplicate是在插入的时候如果主键冲突就执行更新操作

      let flag = 0
      for (let i = 0; i < res.rows.length; i++) {
        getUserInfo({ adminId: res.rows[i].adminId, userId: res.rows[i].userId }).then(data => {
          flag++
          res.rows[i]['user'] = data.user
          res.rows[i]['admin'] = data.admin
          res.rows[i].read = res.rows[i].read ? true : false
          if (flag === res.rows.length) {
            resolve(res)
          }
        })
      }
    })
  }
  const res = await allFn()
  ctx.success({
    total: res.count, // 总页数
    pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
    page: parseInt(page), // 页码
    size: parseInt(size), // 页数
    list: res.rows
  })
}

// 获取用户信息
function getUserInfo({ userId, adminId }) {
  return new Promise(async(resolve) => {
    const admin_data = await User.findOne({ where: { id: adminId }})
    const user_data = await ShopUser.findOne({ where: { userId }})
    const admin_avatar = await getFile(admin_data.avatar)
    const user_avatar = await getFile(user_data.avatar)
    admin_data['avatar'] = admin_avatar
    user_data['avatar'] = user_avatar
    resolve({
      admin: {
        userName: admin_data.userName,
        avatar: admin_data.avatar[0].url
      },
      user: {
        userName: user_data.userName,
        avatar: user_data.avatar[0].url
      }
    })
  })
}
